﻿using Serilog;
using Serilog.Configuration;
using Serilog.Events;
using Serilog.Formatting.Display;
using Serilog.Sinks.PeriodicBatching;
using System;
using NetMicro.Trace.Const;
using NetMicro.Trace.Email;

namespace NetMicro.Trace
{

    public static class LoggerConfigurationEmailExtensions
    {



        const int DefaultBatchPostingLimit = 100;
        static readonly TimeSpan DefaultPeriod = TimeSpan.FromSeconds(30);

        /// <summary>
        /// serilog 发送邮件插槽
        /// </summary>
        /// <param name="loggerConfiguration"></param>
        /// <param name="connectionInfo"></param>
        /// <param name="outputTemplate"></param>
        /// <param name="restrictedToMinimumLevel"></param>
        /// <param name="batchPostingLimit"></param>
        /// <param name="period"></param>
        /// <param name="formatProvider"></param>
        /// <param name="mailSubject"></param>
        /// <returns></returns>
        public static LoggerConfiguration Email(
            this LoggerSinkConfiguration loggerConfiguration,
            EmailConnectionInfo connectionInfo,
            string outputTemplate = Penetrates.DefaultOutputTemplate,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            int batchPostingLimit = DefaultBatchPostingLimit,
            TimeSpan? period = null,
            IFormatProvider formatProvider = null,
            string mailSubject = null)
        {
            if (connectionInfo == null) throw new ArgumentNullException("connectionInfo");

            if (!string.IsNullOrEmpty(connectionInfo.EmailSubject))
            {
                mailSubject = connectionInfo.EmailSubject;
            }

            var batchingPeriod = period ?? DefaultPeriod;
            var textFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
            var mailSubjectFormatter = new MessageTemplateTextFormatter(mailSubject, formatProvider);

            var batchingOptions = new PeriodicBatchingSinkOptions
            {
                BatchSizeLimit = batchPostingLimit,
                Period = batchingPeriod,
                EagerlyEmitFirstEvent = false,  // 设置false 发送邮件不使用此事件
                QueueLimit = 10000
            };
            var batchingSink = new PeriodicBatchingSink(new EmailSink(connectionInfo, textFormatter, mailSubjectFormatter), batchingOptions);

            return loggerConfiguration.Sink(batchingSink, restrictedToMinimumLevel);
        }


    }
}
